package com.example.demo.service.impl;

import com.example.demo.mapper.AddressMapper;
import com.example.demo.pojo.Address;
import com.example.demo.pojo.Pets;
import com.example.demo.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class AddressServiceImpl implements IAddressService {
	@Autowired
	AddressMapper addressMapper ;
	@Override
	public void save(Address address) {
		if (address.getIsDefault()) {
			// 获取当前用户的ID
			Integer userID = address.getUserID();
			// 获取所有其他默认地址并设置为非默认
			List<Address> defaultAddresses = addressMapper.listDefault(userID);
			for (Address otherAddress : defaultAddresses) {
				otherAddress.setIsDefault(false);
				addressMapper.updateById(otherAddress);
			}
		}
		address.setCreateTime(LocalDate.now());
		addressMapper.save(address);
	}

	@Override
	public void update(Address address) {
		if (address.getIsDefault()) {
			// 获取当前用户的ID
			Integer userID = address.getUserID();
			// 获取所有其他默认地址并设置为非默认
			List<Address> defaultAddresses = addressMapper.listDefault(userID);
			for (Address otherAddress : defaultAddresses) {
				otherAddress.setIsDefault(false);
				addressMapper.updateById(otherAddress);
			}
		}
		address.setUpdateTime(LocalDate.now());
		addressMapper.updateById(address);
	}

	@Override
	public  List<Address>findAll(Integer userID)
	{
		return addressMapper.list(userID);
	}

	@Override
	public List<Address> findSingle(Integer userID, Integer addressID) {
		return addressMapper.findSingle(userID,addressID);
	}

	@Override
	public void removeAddressItem(Integer addressID) {
		 addressMapper.remove(addressID);
	}

	@Override
	public List<Address> findDefault(Integer userID) {
		return addressMapper.listDefault(userID);
	}
}
